package com.choupin.choupin.service.impl;

import com.choupin.choupin.service.IPhoneCodeService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import java.util.Random;
import java.util.concurrent.TimeUnit;


@SuppressWarnings("ALL")
@Service
public class PhoneCodeServiceImpl  implements IPhoneCodeService {

     @Autowired
    private StringRedisTemplate stringRedisTemplate;

    private static final String PHONE_CODE_KEY = "phone_code:";
    private static final int CODE_LENGTH = 6;

    @Override
    public String generatePhoneCode(String phoneNumber) {
        Random random = new Random();
        StringBuilder code = new StringBuilder();
        for (int i = 0; i < CODE_LENGTH; i++) {
            code.append(random.nextInt(10));
        }
        stringRedisTemplate.opsForValue().set(PHONE_CODE_KEY + phoneNumber, code.toString(), 5, TimeUnit.MINUTES);
        return code.toString();
    }

    @Override
    public boolean validatePhoneCode(String phoneNumber, String inputCode) {
        String storedCode = stringRedisTemplate.opsForValue().get(PHONE_CODE_KEY + phoneNumber);
        return storedCode != null && storedCode.equals(inputCode);
    }
}
